#include "rpcclient.h"

#include <google/protobuf/descriptor.h>
#include <google/protobuf/service.h>
#include "rpcheader.pb.h"
#include "tinyrpc/base/stringUtil.h"
#include "tinyrpc/net/inetaddress.h"

#include <netinet/in.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>

namespace TinyRPC{

// 所有通过stub 代理对象调用rpc的方法， 都走到这里了，统一做rpc方法调用的数据序列化
void TinyRPCClient::CallMethod(const google::protobuf::MethodDescriptor* method,
                    google::protobuf::RpcController* controller, const google::protobuf::Message* request,
                    google::protobuf::Message* response, google::protobuf::Closure* done)
{
    const google::protobuf::ServiceDescriptor * sd = method->service();
    std::string service_name = sd->name();
    std::string method_name = method->name();

    std::string args_str;
    request->SerializeToString(&args_str);

    TinyRpcHeader rpcHeader;
    rpcHeader.set_service_name(service_name);
    rpcHeader.set_method_name(method_name);
    rpcHeader.set_args_size(args_str.size());

    uint32_t header_size = 0;
    std::string rpc_header_str;
    rpcHeader.SerializeToString(&rpc_header_str);
    header_size = rpc_header_str.size();

    std::string send_rpc_str;
    send_rpc_str.insert(0, std::string((char*)&header_size, 4));
    send_rpc_str += rpc_header_str;
    send_rpc_str += args_str;

    // 先使用tcp发送消息
    int clientfd = socket(AF_INET, SOCK_STREAM, 0);

    

    struct sockaddr_in server_addr = m_serviceMap[service_name].m_servers[0].getSockAddr();
    // server_addr.sin_family = AF_INET;
    // server_addr.sin_addr.s_addr = inet_addr(ip.c_str());
    // server_addr.sin_port = htons(port);

    int rt = connect(clientfd, (struct sockaddr*)&server_addr, (socklen_t) sizeof(server_addr));

    send(clientfd, send_rpc_str.c_str(), send_rpc_str.size(), 0);

    char buf[1024] = {0};
    int recv_size = recv(clientfd, buf, 1024, 0);
    std::string response_str(buf, 0, recv_size);
    response->ParseFromString(response_str);
    close(clientfd);
}


void TinyRPCClient::registServiceStub(::google::protobuf::Service* service){
    const google::protobuf::ServiceDescriptor * serviceDescrip = service->GetDescriptor();
    std::string serviceName = serviceDescrip->name();

    int methodCount = serviceDescrip->method_count();
    ServiceInfo serviceInfo;
    for(int i=0;i<methodCount; i++){
        
        serviceInfo.m_service = service;
        const google::protobuf::MethodDescriptor * methodDescrip = serviceDescrip->method(i);
        serviceInfo.m_methodMap.emplace(methodDescrip->name(), methodDescrip);  
        
    }
    m_serviceMap.insert({serviceName, serviceInfo});

    initRedis();
    //getNextLoop()->runInLoop(Task(std::bind(&TinyRPCClient::keyEventsubscribe, this), true));
}


void TinyRPCClient::initRedis(){
    for(auto& it : m_serviceMap){
        std::string serviceName = it.first;
        std::vector<std::string> serviceServers = m_redisClient.hgetall("TinyRPC:" + serviceName);

        //splitString(str, serviceServers, "\r\n");
        for(int i=0;i<serviceServers.size(); i+=2){
            if(m_redisClient.exists("TinyRPC:" + serviceName + ":" + serviceServers[i])){
                std::vector<std::string> strs;
                splitString(serviceServers[i], strs, ":");
                m_serviceMap[serviceName].m_servers.push_back(INetAddress(strs[0], boost::lexical_cast<int>(strs[1])));
                m_subscribeChannels.push_back("TinyRPC:" + serviceName + ":" + serviceServers[i]);
            }else{
                m_redisClient.hdel("TinyRPC:" + serviceName, serviceServers[i]);
            }
            
        }
    }

}

/**
 * 运行在协程里面
 */
void TinyRPCClient::keyEventsubscribe(){
    INetAddress redisAddress;
    SocketChannel socketChannel;
    socketChannel.connect(redisAddress);
    while (1)
    {
        BufferPtr buffer = m_redisClient.coroutine_subscribe(socketChannel, m_subscribeChannels);
    
        std::string notice = buffer->read();

        // 新增
        std::string serviceName;
        std::string str = m_redisClient.get(serviceName);
        // 添加进入
        // 过期删除
    }
    
    


}

}